<?php
/**
 * @version			$Id$
 * @author			Richard Asp
 * @package			Joomla
 * @subpackage		gnudoor
 * @copyright		(C) 2010 gnudoor LLC
 * @license      GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport( 'joomla.application.component.model' );

class GnudoorModelAppointments extends JModel
{
		public $events;
		public $timezone;
		public $kTimeslots;
	
		function __construct() {
            parent::__construct();
		}
		
		function &getSlots() {
		$query =  ' SELECT * '
				. ' FROM #__pbbooking_slots '
				. ' ORDER by id '
				;
		$this->_db->setQuery( $query );
		return $this->_db->loadAssocList();
		}
				
		function &getCals() {		
			$query = "SELECT path from #__pbbooking_cals where in_cal=1";
			$this->_db->setQuery($query);
			return $this->_db->loadResultArray();
		}

		function &getTreats() {		
			$query="SELECT * from #__pbbooking_treatments";
			$this->_db->setQuery($query);
			return $this->_db->loadAssocList();
		}
		
		function &getConfigs() {
			$query = "SELECT * from #__pbbooking_config";
			$this->_db->setQuery($query);
			return $this->_db->loadAssocList();
		}

		function &getFields() {
			$query = "SELECT * FROM #__pbbooking_customfields";
			$this->_db->setQuery($query);
			return $this->_db->loadAssocList();
		}	

		function _isFree($date,$timeslot){
			global $timezone;
		//	global $events;
			date_default_timezone_set($this->timezone);
			
			$eventstart = clone $date;
			$eventend = clone $date;
			$eventstart->setTime($this->kTimeslots[$timeslot]['start_hour'],$this->kTimeslots[$timeslot]['start_min']);
			$eventend->setTime($this->kTimeslots[$timeslot]['end_hour'],$this->kTimeslots[$timeslot]['end_min']);
				
			$free = true;
			foreach($this->events as $event) {
				//check for normal events
				if ($event->dtend >= $eventstart && $event->dtend <= $eventend) {
					$free = false;
				}
				
				//check for multi day events
				if ($event->dtstart <= $eventstart && $event->dtend >= $eventend) {
					$free = false;
				}
				
				//check for recurrance
				$checkrecur = false;
				if ($event->recurring) {
					if (gettype($event->recurring['until']) != "integer") {
						$until = $event->recurring['until'];
						if ($until > $eventstart) {
							$checkrecur = true;
						}
					} else {
						$checkrecur = true;
					}
					
					if ($checkrecur) {
						$checkstart = clone $event->dtstart;
						$checkend = clone $event->dtend;
						while ($checkstart <= $eventstart) {
							if ($checkend >= $eventstart && $checkend <= $eventend) {
								$free = false;
							}
							$modstring = sprintf("+%s day",7*$event->recurring['interval']);
							$checkstart->modify($modstring);
							$checkend->modify($modstring);
						}
					}
				}
			}
			return $free;
		}
// public $events;
//public $timezone;
//public $kTimeslots;

function parseCalendar($cals) {
	global $timezone;
	date_default_timezone_set($this->timezone);

	$events = Array();
	
	foreach($cals as $cal)
	{
		$path_parts = pathinfo($cal);
		if ($path_parts['dirname'] == '.') {
			#the cal is in the component subdir so add relevant info to path
			$realpath = JPATH_SITE.DS.'components'.DS.'com_gnudoor'.DS.$cal;
			$cal = $realpath;
		}
		
		$file = @fopen($cal,"r");
	
		$string = "";

		$inevent = false;
		$i = 0;


		$curr_summary = "";
		$curr_dtend = "";
		$curr_dtstart = "";
		$recurring = false;
		$recarr = Array();

		while(!feof($file)) {
	
			$line = fgets($file);
	
			if (preg_match("/^BEGIN:VEVENT/",$line)==1) {
				//we have started an event
				$inevent = true;
				$i = $i +1;
			}
	
			if ($inevent) {
				if (preg_match("/^SUMMARY:/",$line) == 1) {
					$curr_summary = str_replace('SUMMARY:',"",$line);
				}
				if (preg_match("/^DTEND;TZID=/",$line) == 1) {
					//this captures on cals where we have TZID in the code
					$temp = str_replace('DTEND;TZID='.$this->timezone.':',"",$line);
					$curr_dtend= date_create($temp);
				}
		
				if (preg_match("/^DTSTART;TZID=/",$line) == 1) {
					//echo this captues on cals where we have TZID in the code
					$temp = str_replace("DTSTART;TZID=".$this->timezone.":","",$line);
					$curr_dtstart= date_create($temp);
				}

				if (preg_match("/^DTEND;VALUE=DATE-TIME/",$line) == 1) {
					//this captures on cals where we have zulu time
					$temp = str_replace('DTEND;VALUE=DATE-TIME:',"",$line);
					$temp1=str_replace('Z',"",$temp);
					$curr_dtend= date_create($temp1);
				}
				
				if (preg_match("/^DTSTART;VALUE=DATE-TIME/",$line) == 1) {
					//this captures on cals where we have zulu time
					$temp = str_replace('DTSTART;VALUE=DATE-TIME:',"",$line);
					$curr_dtstart= date_create($temp);
				}
				
				if (preg_match("/^RRULE:/",$line)==1) {
					//we are in a recurring event
					$temp = str_replace('RRULE:',"",$line);
					$recarr = explode(";",$temp);
					$recurring = true;
				}

		
				if (preg_match("/^END:VEVENT/",$line) == 1) {
					//we have reached the close of the event
					$inevent = false;
					//$event = Array("summary" => $curr_summary, "dtend" => $curr_dtend, "dtstart"=>$curr_dtstart);
					$event = new event();
					$event->summary = $curr_summary;
					$event->dtend = $curr_dtend;
					$event->dtstart = $curr_dtstart;
//					$this->summary = $curr_summary;
//					$this->dtend = $curr_dtend;
//					$this->dtstart = $curr_dtstart;
					if ($recurring) {
						$recurring = false;
						$interval = str_replace('INTERVAL=',"",$recarr[1]);
						
						//is until defined?
						if (isset($recarr[2])) {
							if (preg_match("/^UNTIL=/",$recarr[2])==1) {
								$temp=str_replace('Z',"",$recarr[2]);
								$untilstring = str_replace("UNTIL=","",$temp);
								$untildate= date_create($untilstring);
								$event->recurring = Array ("frequency"=>"week","interval"=>$interval,"until"=>$untildate);
//								$this->recurring = Array ("frequency"=>"week","interval"=>$interval,"until"=>$untildate);
							}
						} else {
							$event->recurring = Array ("frequency"=>"week","interval"=>$interval,"until"=>0);
//							$this->recurring = Array ("frequency"=>"week","interval"=>$interval,"until"=>0);
						}
						
						
					}
					$events[]=$event;
				}
			}	
		}
	}
	
	foreach($events as $row) {
		$dtstart[]=$row->dtstart;
	}

	//gives me an array of events going newest to oldest
	if (count($events) > 0) {
		array_multisort($dtstart,SORT_DESC,$events);
	}
	
	$this->events = $events;
}

function isFree($date,$timeslot){
	global $timezone;
	date_default_timezone_set($this->timezone);
	
	$eventstart = clone $date;
	$eventend = clone $date;
	$eventstart->setTime($this->kTimeslots[$timeslot]['start_hour'],$this->kTimeslots[$timeslot]['start_min']);
	$eventend->setTime($this->kTimeslots[$timeslot]['end_hour'],$this->kTimeslots[$timeslot]['end_min']);
		
	$free = true;
	foreach($this->events as $event) {
		//check for normal events
		if ($event->dtend >= $eventstart && $event->dtend <= $eventend) {
			$free = false;
		}
		
		//check for multi day events
		if ($event->dtstart <= $eventstart && $event->dtend >= $eventend) {
			$free = false;
		}
		
		//check for recurrance
		$checkrecur = false;
		if ($event->recurring) {
			if (gettype($event->recurring['until']) != "integer") {
				$until = $event->recurring['until'];
				if ($until > $eventstart) {
					$checkrecur = true;
				}
			} else {
				$checkrecur = true;
			}
			
			if ($checkrecur) {
				$checkstart = clone $event->dtstart;
				$checkend = clone $event->dtend;
				while ($checkstart <= $eventstart) {
					if ($checkend >= $eventstart && $checkend <= $eventend) {
						$free = false;
					}
					$modstring = sprintf("+%s day",7*$event->recurring['interval']);
					$checkstart->modify($modstring);
					$checkend->modify($modstring);
				}
			}
		}
	}
	return $free;
}

function writeEvent($event,$calfile) {
	global $timezone;
	date_default_timezone_set($this->timezone);
	
	global $kOutcal;
	//BEGIN:VEVENT
	//DTEND;VALUE=DATE-TIME:20100426T172429Z
	//DTSTART;VALUE=DATE-TIME:20100426T162429
	//SUMMARY:New Event
	//END:VEVENT
	
	$path_parts = pathinfo($calfile);
	if ($path_parts['dirname'] == '.') {
		#the cal is in the component subdir so add relevant info to path
		$realpath = JPATH_SITE.DS.'components'.DS.'com_gnudoor'.DS.$calfile;
		$calfile = $realpath;
	}
	
	$file = @fopen($calfile,"r");
	$lines = Array();
	$i = 0;
	$insert=0;
	while(!feof($file)) {
		//read entire file into memory and if line == BEGIN:VTIMEZONE then note the line in $i
		$line = fgets($file);
		if (preg_match("/^BEGIN:VTIMEZONE/",$line) == 1) {
			$insert=$i;
		}
		$i++;
		$lines[]=$line;
	}
	fclose($file);
	
	//slice array from insert to end
	//add elements recursively to end of array and merge again
	$arr1 = array_slice($lines,0,$insert);
	$arr2 = array_slice($lines,$insert,(count($lines)-$insert));
	//pop new elements to end of $arr1
	$arr1[] = "BEGIN:VEVENT\n";
	$arr1[] = sprintf("DTEND;VALUE=DATE-TIME:%sT%sZ\n",date_format($event->dtend,'Ymd'),date_format($event->dtend,'His'));
	$arr1[] = sprintf("DTSTART;VALUE=DATE-TIME:%sT%s\n",date_format($event->dtstart,'Ymd'),date_format($event->dtstart,'His'));
	$arr1[]=sprintf("SUMMARY:%s\n",$event->summary);
	$arr1[]="DESCRIPTION:$event->description\n";
	$arr1[]="END:VEVENT\n";
	
	$lines = array_merge($arr1,$arr2);
	
	$file = @fopen($calfile,"w");
	foreach($lines as $line) {
		fwrite($file,$line);
	}
	
	fclose($file);
}
	public $summary;
	public $dtend;
	public $dtstart;
	// public $kTimeslots;
	public $recurring;
	public $description;
	
	function setProperties($date,$timeslot,$duration,$summary) {
		global $kTimeslots;
		$this->summary = $summary;
		$dtstart = clone $date;
		$dtstart->setTime($this->kTimeslots[$timeslot]['start_hour'],$this->kTimeslots[$timeslot]['start_min']);
		$dtend = clone $dtstart;
		$dtend->modify('+'.$duration.' minutes');
		$this->dtend = $dtend;
		$this->dtstart = $dtstart;
	}
	
	function setDescription($customfields) {
		#function to set the description to contact a list of custom fields
		if (count($customfields>0)) {
			foreach ($customfields as $field) {
				$this->description .= sprintf('%s = %s\n',$field['varname'],$field['data']);
			}
		}
	}

}
?>